package com.rfid.assistant.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.OpenableColumns;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.rfid.DirectoryBean;
import com.rfid.assistant.R;
import com.rfid.assistant.activity.adapter.FileAdapter;
import com.rfid.assistant.activity.adapter.OnItemClickListener;
import com.rfid.assistant.activity.adapter.SendMsgAdapter;
import com.rfid.config.ConstantsConfig;
import com.rfid.event.ProgressEvent;
import com.rfid.event.SendStatus;
import com.rfid.sockethelper.ClientManager;
import com.rfid.sockethelper.ClientSocketHelper;
import com.rfid.sockethelper.IOHelper;
import com.rfid.sockethelper.SocketBase;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public abstract class SRBaseActivity extends AppCompatActivity implements SocketBase.OnReceiveListener, OnItemClickListener {

    String mIp;
    private static final int FILE_REQUEST_CODE = 1;
    @BindView(R.id.edit)
    EditText mEditText;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    SendMsgAdapter mAdapter;
    List<String> mMessages = new ArrayList<>();
    Handler mHandler = new Handler();

    FileAdapter mFileAdapter;
    AlertDialog mAlertDialog;
    boolean sendToSet;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mAdapter = new SendMsgAdapter(mMessages);
        mAdapter.setListener(this);
        mRecyclerView.setAdapter(mAdapter);
        mFileAdapter = new FileAdapter(this,new DirectoryBean());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStatus(SendStatus status) {
        System.out.println(status);
        int st = status.status;
        if (status.cmd == IOHelper.CMD_SEND_FILE) {
            if (st == SendStatus.OK ) {
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
                mMessages.add(0,"文件发送成功");
            } else {
                mMessages.add(0,"文件发送失败");
            }
            mAdapter.notifyDataSetChanged();
        } else if (status.cmd == IOHelper.CMD_SET_FILE) {
            if (st == SendStatus.OK ) {
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
                mMessages.add(0,"指定远端目录文件发送成功");
            } else {
                mMessages.add(0,"指定远端目录文件发送失败");
            }
            mAdapter.notifyDataSetChanged();
        } else if (status.cmd == IOHelper.CMD_DELETE_FILE) {
            if (st == SendStatus.OK ) {
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
                mMessages.add(0,"删除文件指令发送成功");
            } else {
                mMessages.add(0,"删除文件指令发送失败");
            }
            mAdapter.notifyDataSetChanged();
        } else {
            if (status.status != SendStatus.OK) {
                Toast.makeText(this, "发送失败 > " + status.status, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProgress(ProgressEvent event) {
        System.out.println(event);
        String msg = (event.type == ProgressEvent.TYPE_READ?"接收：":"发送：");
        msg = msg + Math.round(event.current/(float)event.total*10000)/100 + "%";
        if (mMessages.size() > 0 && mMessages.get(0).contains("%")) {
            mMessages.remove(0);
            mMessages.add(0,msg);
        } else {
            mMessages.add(0,msg);
        }
        mAdapter.notifyDataSetChanged();
    }

    public void send(View view) {
    }

    public void chooseFile(View view) {
        openFileSelector();
    }


    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {
        System.out.println(cmd + "--" + ip +"--" + text[0]);
//        Toast.makeText(this,text,Toast.LENGTH_SHORT).show();
        if (cmd == IOHelper.CMD_SEND_FILE) {
            mMessages.add(0,"接收文件：" + ConstantsConfig.directoryPath + "" + new File(text[0].toString()).getName());
        } else if (cmd == IOHelper.CMD_STR) {
            mMessages.add(0,text[0].toString());
        } else if (cmd == IOHelper.CMD_SEND_FILE_LIST) {
            Gson gson = new Gson();
            DirectoryBean bean = gson.fromJson(text[0].toString(),DirectoryBean.class);
            mFileAdapter.changeDir(bean);
            if (mAlertDialog == null) {
                showRemoteFileList();
            } else if (!mAlertDialog.isShowing()) {
                mAlertDialog.show();
            }
            mAlertDialog.setTitle(bean.getPath()+"（按返回回到上一级）");
        } else if (cmd == IOHelper.CMD_REQ_FILE) {
            mMessages.add(0,"远端请求文件：" + text[0].toString());
        } else if (cmd == IOHelper.CMD_SET_FILE) {
            mMessages.add(0,"接收远端文件到指定目录：" + text[0]);
        } else if (cmd == IOHelper.CMD_DELETE_FILE) {
            mMessages.add(0,"删除文件：" + text[0]);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onConnect(String ip, boolean connect) {
        mIp = ip;
    }

    @Override
    public void onClick(int pos) {
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setText(mMessages.get(pos));
        Toast.makeText(this,"已复制文本",Toast.LENGTH_SHORT).show();
    }

    public void openFileSelector() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        startActivityForResult(intent, FILE_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Uri fileUri = data.getData();
            // 处理文件选择结果
            handleSelectedFile(fileUri);
        }
    }

    protected  void handleSelectedFile(Uri uri){
        String path = uri.getPath();
        path = path.replace("external_files","sdcard");
        mMessages.add(0,"发送文件：" + getName(this,uri));
        mAdapter.notifyDataSetChanged();
    }

    private String getName(Context context,Uri uri) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int displayNameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            if (!cursor.isNull(displayNameIndex)) {
                String fileName = cursor.getString(displayNameIndex);
                return fileName;
            }
        }
        return null;
    }

    public void showRemoteFileList() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("远程文件（按返回回到上一级）")
               .setCancelable(false)
               .setSingleChoiceItems(mFileAdapter, 0, new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       DirectoryBean.FileEntity entity = mFileAdapter.getItem(which);
                       if (!entity.isFile()) {
                           requestDir(entity.getPath());
                       } else {
                           if (sendToSet) {
                               return;
                           }
                           new AlertDialog.Builder(SRBaseActivity.this).setTitle("获取文件").setMessage("是否拉取文件到本地？")
                                   .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                       @Override
                                       public void onClick(DialogInterface dialog, int which) {
                                           mMessages.add(0,"拉取远端文件：" + entity.getPath());
                                            requestFile(entity.getPath());
                                            mAlertDialog.dismiss();
                                            mAdapter.notifyDataSetChanged();
                                       }
                                   }).setNegativeButton("取消",null).show();
                       }
                   }
               })
               .setOnKeyListener(new DialogInterface.OnKeyListener() {
                   @Override
                   public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                       if (keyCode == KeyEvent.KEYCODE_BACK) {
                           DirectoryBean bean = mFileAdapter.getCurrentDir();
                           File c = new File(bean.getPath());
                           File parent = c.getParentFile();
                           System.out.println("KEYCODE_BACK > " + c.getName());
                           if (!c.getName().equals("sdcard")) {
                               requestDir(parent.getPath());
                           }
                       }
                       return true;
                   }
               })
                .setNegativeButton("退出",null);
        if (sendToSet) {
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    onSelectDir(mFileAdapter.getCurrentDir().getPath());
                }
            });
        }
        mAlertDialog = builder.show();
        if (!sendToSet) {
            mAlertDialog.getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    DirectoryBean.FileEntity entity = mFileAdapter.getItem(position);
                    System.out.println("onItemLongClick > " + entity.getPath());
                    new AlertDialog.Builder(SRBaseActivity.this).setTitle("删除文件").setMessage("是否删除所选？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mMessages.add(0,"删除远端文件：" + entity.getPath());
                                    deleteRemoteFile(entity.getPath());
                                    mAlertDialog.dismiss();
                                    mAdapter.notifyDataSetChanged();
                                }
                            }).setNegativeButton("取消",null).show();
                    return false;
                }
            });
        }
    }

    protected abstract void deleteRemoteFile(String path);

    protected void onSelectDir(String path) {
    }

    protected abstract void requestFile(String path);

    protected abstract void requestDir(String path);

    public void remote(View view) {
        requestDir("/sdcard/");
    }
}
